package ddd.ajava.chapter5.question2.udp;
import java.net.*;
import java.io.*;
import java.util.*;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;

public class UdpThread implements Runnable{
	PrintWriter write;
	DatagramSocket getSocket ;
	DatagramSocket getSocket1;
 
    public UdpThread(DatagramSocket getSocket, DatagramSocket getSocket1) {
		this.getSocket=getSocket;
    	this.getSocket1=getSocket1;
	}
	public void run(){//一个会话的内容
    	while(true){
			try{
				byte[] buffer1 = new byte[4033];
				DatagramPacket getPacket1 = new DatagramPacket(buffer1, buffer1.length);  // 通过套接字接收文件名数据  
				getSocket1.receive(getPacket1); //收到发送端发送来的文件名数据报
				String fileName = new String(buffer1, 0, getPacket1.getLength());//具体名字	
				//*得到文件名
				
				System.out.println(fileName+"\n");
//				File file=new File("uploadUdp",fileName);
				File file=new File(fileName);
				write=new PrintWriter(file);//写入一个文件
				
				byte[] buffer = new byte[4033];  // 把得到的数据报放入这个缓冲区
				DatagramPacket getPacket = new DatagramPacket(buffer, buffer.length);  // 通过套接字接收数据  
				getSocket.receive(getPacket); //收到发送端发送来的数据报
				String getMes = new String(buffer, 0, getPacket.getLength());//具体信息 		
				write.print(getMes);
				
				// 通过数据报得到发送方的套接字地址  
				SocketAddress sendAddress = getPacket.getSocketAddress();  
				String feedback = "我收到了！";  //确认消息
				byte[] backBuf = feedback.getBytes();  
				DatagramPacket sendPacket = new DatagramPacket(backBuf, backBuf.length, sendAddress);  
				getSocket.send(sendPacket);  
				if(getPacket1.getLength()==0){
					break;
				}
			     getSocket.close();  
			     write.close();	      
			}catch(Exception e){
				
			}      
        }
   }
    public static void FileInformation(String texts){//显示收到的文本
		JFrame showInfo=new JFrame();
		JPanel jp=new JPanel();
		JTextArea text=new JTextArea(20,20);//文本区
		text.append(texts);//输入
		jp.add(text);
		showInfo.add(jp);
		
		showInfo.setTitle("服务端相应！");
		showInfo.setVisible(true);
		showInfo.setSize(300,100);
		showInfo.setLocation(500, 500);
		showInfo.setDefaultCloseOperation(1);
	}
}
